package com.yinhai.project.controller;

import com.yinhai.core.app.ta3.web.controller.BaseController;
import com.yinhai.core.common.api.base.IConstants;
import com.yinhai.core.common.api.config.impl.SysConfig;
import com.yinhai.core.common.api.util.RSAUtils;
import com.yinhai.core.common.api.util.ValidateUtil;
import com.yinhai.modules.authority.api.vo.MenuTreeNode;
import com.yinhai.modules.authority.api.vo.MenuVo;
import com.yinhai.modules.codetable.api.util.CodeTableUtil;
import com.yinhai.modules.org.api.bpo.IUserBpo;
import com.yinhai.modules.org.api.password.PasswordEncrypter;
import com.yinhai.modules.org.api.vo.org.ResetPasswordParamVo;
import com.yinhai.modules.org.api.vo.user.UserVo;
import com.yinhai.modules.security.api.util.SecurityUtil;
import com.yinhai.modules.security.api.vo.UserAccountInfo;
import com.yinhai.modules.sysapp.domain.po.SignRecordPo;
import com.yinhai.ta3.sysapp.signrecord.service.SignRecordService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController extends BaseController {

    @Resource
    private SignRecordService signRecordService;

    @Resource
    private IUserBpo userBpo;

    @Resource
    private PasswordEncrypter passwordEncrypter;

    @RequestMapping("indexAction.do")
    public String index(HttpServletRequest request) throws IOException {
        List<MenuVo> list = SecurityUtil.getCurrentUserPermissionMenus(request.getSession());
        if (ValidateUtil.isNotEmpty(list)) {
            MenuTreeNode treeNode = MenuTreeNode.createTreeWithFilter(list,true);
            List menuList = new ArrayList();
            List secondMenuList = treeNode.getChildNode();
            request.setAttribute("menuList", secondMenuList==null?new ArrayList():secondMenuList);
        } else {
            request.setAttribute("menuList", new ArrayList());
        }
        SignRecordPo srd = signRecordService.queryLastSign(getTaDto());
        request.getSession().setAttribute("signstate", srd == null ? "0" : srd.getSignstate());
        request.setAttribute("signstate", request.getSession().getAttribute("signstate"));
        return "index";
    }

    /**
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("indexAction!changePassword.do")
    public String changePasswordWidthCurrent(HttpServletRequest request) throws Exception {
        if (ValidateUtil.isEmpty(getTaDto().getAsString("oldPass"))) {
            return JSON;
        }
        if (!"1".equals(request.getParameter("indexChangePass"))) {
            String captcha = (String) request.getSession().getAttribute(IConstants.CHECKCODE_KEY);
            request.getSession().removeAttribute(IConstants.CHECKCODE_KEY);//获取之后删除验证码
            if(ValidateUtil.isEmpty(captcha)){
                setMessage("验证码错误", "error");
                return JSON;
            }
            if ( !captcha.equals(getTaDto().getAsString("checkCodePass"))) {
                setMessage("验证码错误", "error");
                return JSON;
            }
        }
        String loginid = getTaDto().getAsString("loginId");
        UserVo vo = null;
        if (ValidateUtil.isEmpty(loginid)) {//表示已经登录
            Long userId = getTaDto().getUser().getUserid();
            vo = userBpo.getUserByUserId(userId);
        } else {//登录页修改密码
            vo = userBpo.getUserByLoginId(loginid);
        }
        //当缓存和数据库中没有查询出此人，表示没有此人
        if (vo == null) {
            setMessage("查无此人，请检查登录号是否正确", "error");
            return JSON;
        }
        if (ValidateUtil.isEmpty(vo)) {
            setMessage("不存在此用户", "error");
            return JSON;
        }
        loginid = vo.getLoginid();
        String oldPass = getTaDto().getAsString("oldPass");
        boolean rsa = SysConfig.getSysConfigToBoolean("passwordRSA", false);
        if (rsa) {
            oldPass = RSAUtils.descryptWidthEncode(oldPass);
        }
        if (!passwordEncrypter.encodePassword(oldPass, loginid).equals(vo.getPassword().toString())) {
            setMessage("原始密码错误", "error");
            return JSON;
        }
        ResetPasswordParamVo paramVo = new ResetPasswordParamVo();
        paramVo.setFirstFlag("true");
        paramVo.setNewPassword(getTaDto().getAsString("newPass"));
        if (rsa) {
            paramVo.setNewPassword(RSAUtils.descryptWidthEncode(getTaDto().getAsString("newPass")));
        }
        List<Long> userIds = new ArrayList<Long>();
        userIds.add(vo.getUserid());
        paramVo.setUserIds(userIds);
        userBpo.resetPassword(paramVo, 1L, 1L);
        setMessage("修改密码成功！", "success");
        return JSON;
    }

    /**
     * 获取码表数据
     * add by zzb
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("indexAction!getCacheByCollection.do")
    public String getCacheByCollection(String collection, HttpServletRequest request) throws Exception {
        String orgid = null;
        UserAccountInfo user = SecurityUtil.getUserAccountInfo(request);
        if (user != null) {
            orgid = user.getOrgId();
        }
        String codeListJson = CodeTableUtil.getCodeListJson(collection, orgid);
        setData("codeListJson", codeListJson);
        return JSON;
    }


    @RequestMapping("websocket.do")
    public String websocket() {
        return "websocket/websocket_test";
    }

    @RequestMapping("websocket2.do")
    public String websocket2() {
        return "websocket/websocket_test2";
    }
}
